/* Written By : Chang Hyun Park
 * Student ID : 2007002320
 * Subject	  : Data Communication
 * File Name  : client.java
 */
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class client
{
//	static int ackCount=10;
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception
	{
		DatagramSocket clientSocket;
		InetAddress remoteAddress;
		int remotePort, myPort; 
		Receive recvThread;
		Send sendThread;

		
		//Get the Args and setup remoteAddress and remotePort
		if(args.length!=0)//Filename, IP address, Port
		{
			myPort = Integer.parseInt(args[0]);
			if(args.length==2)
			{
				remoteAddress = InetAddress.getByName(args[1]);
				remotePort = 64444;
			}
			else if(args.length==3)
			{
				remotePort = Integer.parseInt(args[2]);
				remoteAddress = InetAddress.getByName(args[1]);
			}
			else
			{
				remotePort = 64444;
				remoteAddress = InetAddress.getByName("127.0.0.1");
			}
		}
		else
		{
			System.out.println("You must insert this client's Port number, and the remote client's IP address and Port number");
			System.out.println("You didn't insert them from the Command Line as paramters.");
			System.out.print("Please insert the port number to bind this Client to ->");
			Scanner keyboard = new Scanner(System.in);
			myPort = keyboard.nextInt();
			System.out.print("Please insert the IP address to send messages to ->");
			keyboard.nextLine();	//Get rid of the linebreak from above.
			remoteAddress = InetAddress.getByName(keyboard.nextLine());
			System.out.print("Please insert the Port number of the receiving client ->");
			remotePort = keyboard.nextInt();
			keyboard.nextLine();
			
/*			remotePort = 64444;
			remoteAddress = InetAddress.getByName("127.0.0.1");
			myPort = 64777;*/
		}
		
		//Create and bind socket to myPort;
	
		try{
			clientSocket = new DatagramSocket(myPort);
			sendThread = new Send(clientSocket, remoteAddress, remotePort);
			recvThread = new Receive(clientSocket, sendThread);

			
			
			sendThread.start();
			recvThread.start();
		} catch (SocketException e)
		{
			System.out.println("Socket could not be opened, or couldn't be binded to "+myPort+".\n" +
					"Please restart the program with a different Port number");
			e.printStackTrace();
			System.exit(1);
		}
		
	}
/*	public static int getAckCount()
	{	//AckCount is a 2-digit integer!
		if(ackCount==99)
			ackCount = 10;
		else
			ackCount++;
		System.out.println("Ack is "+ackCount);
		return ackCount;
	}*/

}
